<template>
  <div class="app-container">
    <el-button @click="GoBack">返回</el-button>
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick" v-loading="tableLoading">
      <el-tab-pane label="概述" name="0">
        <Summary
          v-if="flag"
          :sunnaryInfo="form"
          :officeOption="officeOption"
          :tagOption="tagOption"
          :hospitalOptions="hospitalOptions"
          :tag="tag"
          ref="Summary"
        ></Summary>
      </el-tab-pane>
      <el-tab-pane
        v-for="(item, index) in medicalInstitutions"
        :name="index + 1 + ''"
        :label="
          item.examTypeName + '(' + (item.examQuesInfos.length + '项' + ')')
        "
        :key="index"
      >
        <h4>{{ item.examTypeName }}({{ item.examQuesInfos.length }}项)</h4>
        <Qualification
          v-if="item.examQuesInfos"
          :QualificationInfo="item.examQuesInfos"
          :quesTypeName="item.quesTypeName"
          :quesSelIds="quesSelIds"
          :examType="item.examType"
          :start="arrnum[index]"
          :number="item.examQuesInfos.length"
          :type="type"
          :activeNameType="item.examType"
          :ref="'child' + index"
          @update="receive"
        ></Qualification>
      </el-tab-pane>
      <el-carousel ref="carousel" :autoplay="false" arrow="never" trigger="click">
        <el-carousel-item v-for="(item, index) in lenthNum" :key="index">
          <!-- {{index}} -->
          <el-button @click="changfn(index)" v-if="index != lenthNum - 1">下一项</el-button>
          <!-- <el-button v-if="index==10&type!=1" @click="Submit">提交</el-button> -->
          <el-button v-if="index == lenthNum - 1" @click="GoBack(index - 1)">返回</el-button>
          <el-button v-if="(index == lenthNum - 1) & (type != 1)" @click="Submit">保存</el-button>
        </el-carousel-item>
      </el-carousel>
    </el-tabs>
  </div>
</template>

<script>
import Summary from "./Summary.vue";
import Qualification from "./Qualification.vue";
import {
  hospitalExamDetail,
  getHospitalExamQues,
  addHospitalExam
} from "@/api/StrictSelection";
import { hospitalList } from "@/api/financialBack";
import { findHospitalTagsList } from "@/api/hospitalLabel";
import { companyList } from "@/api/branchOfficeDropDown";
export default {
  name: "StrictSelectionInfo",
  components: { Summary, Qualification },
  data() {
    return {
      arrnum: [],
      tableLoading: false,
      activeName: 0,
      userId: "",
      type: null,
      tag: null,
      flag: true,
      form: {},
      medicalInstitutions: [],
      activeNameType: 0,
      tabList: [
        // { label: "医疗机构资质", name: "1" },
        // { label: "院感管理", name: "2" },
        // { label: "药事管理", name: "3" },
        // { label: "医疗器械管理", name: "4" },
        // { label: "质控管理", name: "5" },
        // { label: "设施管理", name: "6" },
        // { label: "病历管理", name: "7" },
        // { label: "接诊服务", name: "8" },
        // { label: "医疗服务", name: "9" },
        // { label: "外包服务", name: "10" }
      ],
      serverTab: [],
      quesSelIds: [],
      hospitalOptions: [],
      officeOption: [],
      tagOption: [],
      chooselist: [],
      lenthNum: null
    };
  },
  mounted() {
    this.userId = Number(this.$route.query.userId);
    this.type = Number(this.$route.query.type);
    console.log("this.tag", this.tag);
    if (this.type == 1) {
      this.$route.meta.title = "245详情";
    } else if (this.type == 2) {
      this.$route.meta.title = "245编辑";
    } else if (this.type == 3) {
      this.$route.meta.title = "添加严选结果";
    }

    this.getExamQues();
  },
  created() {
    this.tag = Number(this.$route.query.type);
    // this.flag=true
    this.getHospital();
    this.getCompanyList();
  },
  watch: {
    // "document.body.scrollTop"(val) {
    //   val = 0;
    // }
  },
  //监听tab切换的状态值
  // watch: {
  //   activeName(val, oldVal) {
  //     // 普通的watch监听
  //     console.log("activeName: " + val);
  //     this.activeNameType=val
  //     this.getExamQues()
  //   },
  // },
  methods: {
    receive(val) {
      //   console.log("val", ArrModel);
      //   // this.form.examQuesSelInfos = val;
    },
    //概述及答案
    getDetail() {
      this.tableLoading = true;
      // console.log(this.userId)
      hospitalExamDetail({ id: this.userId }).then(res => {
        this.form = res.data.data;
        // console.log("/////", this.form.examQuesSelInfos);
        this.tableLoading = false;
        let ids = [];
        // console.log(this.medicalInstitutions, 777);
        // console.log(this.form, 88888);

        if (this.form.examQuesSelInfos.length > 0) {
          this.form.examQuesSelInfos.forEach(item => {
            // console.log(11112222, item);
            ids.push({
              quesSelId: item.quesSelId,

              selDescOne: item.quesSelId == 2 ? item.selDesc : "",
              selDescTwo: item.quesSelId == 3 ? item.selDesc : ""
            });
          });

          let arr2 = [];
          // console.log("ids222", ids);
          for (let i = 0; i < this.medicalInstitutions.length; i++) {
            let arr = [];
            for (
              let k = this.medicalInstitutions[i].start;
              k < this.medicalInstitutions[i].end;
              ++k
            ) {
              // console.log("ids", ids[k]);
              arr.push(ids[k]);
            }
            arr2.push(arr);
          }
          // console.log(arr2, 99999);
          // console.log(this.$refs["child0"], this.$refs.child1, this.$refs);
          // let arr =[]
          for (let i = 0; i < this.medicalInstitutions.length; i++) {
            let child = "child" + i;
            this.$refs[child][0].ArrModel = arr2[i];
            // this.$refs[child][0].ArrModel.forEach((item,index)=>{
            //   item.examType = this.$refs["child" + i][0].examType;
            //   item.quesType =this.$refs["child" + i][0].examType + "_" + (index + 1);
            //   this.form.examQuesSelInfos.push(item)
            // })
          }
          this.quesSelIds = ids;
          console.log(ids);
          // console.log('this.$refs[child][0].ArrModel',this.$refs['child'+1][0].ArrModel)
          // console.log('$refs',this.$refs)
        }
      });
    },
    //题目内容
    async getExamQues() {
      this.tableLoading = true;
      let res = await getHospitalExamQues();
      if (res.data.code == 0) {
        this.medicalInstitutions = res.data.data;
        this.lenthNum = this.medicalInstitutions.length + 1;
        // console.log(this.medicalInstitutions, 5555);
        let lastnum = 0;
        let arrnum = [0];
        for (let i = 0; i < this.medicalInstitutions.length; i++) {
          lastnum += this.medicalInstitutions[i].examQuesInfos.length;
          arrnum.push(lastnum);

          //start
          this.medicalInstitutions[i].start = arrnum[i];
          this.medicalInstitutions[i].end =
            arrnum[i] + this.medicalInstitutions[i].examQuesInfos.length;

          // if (i == 0) {
          //   //0
          //   this.medicalInstitutions[i].start = 0;

          //   console.log("this.medicalInstitutions", this.medicalInstitutions);
          // } else {
          //   //1-9
          //   this.medicalInstitutions[i].start =  this.medicalInstitutions[
          //     i -1
          //   ].end;
          // }
        }
        this.arrnum = arrnum;
        // console.log("arrnum", arrnum,this.medicalInstitutions);
        // let newArr = [];
        // let numArr = []; //每个tab栏题目条数 数组
        // console.log(this.medicalInstitutions, 6666);

        // this.medicalInstitutions.forEach((item, index) => {
        //   console.log("item", item);
        //   newArr.push({
        //     num: item.examQuesInfos.length
        //   });
        //   // console.log("newArr", newArr);
        // });
        // newArr.forEach(item => {
        //   // console.log(item.num)
        //   numArr.push(item.num);
        // });
        // console.log(numArr);

        //在题目请求之后再请求选项数据
        this.getDetail();
      }
    },
    //医院名称
    getHospital() {
      hospitalList().then(res => {
        //  console.log(res.data.data)
        if (res.data.data) {
          this.hospitalOptions = res.data.data.map(item => {
            return { value: item.id + "", label: item.name };
          });
        }
      });
    },
    // 获取分公司列表
    getCompanyList() {
      companyList()
        .then(res => {
          const resData = res.data.data;
          const newData = [];
          resData.forEach(e => {
            newData.push({
              value: e.id,
              label: e.name
            });
          });
          this.officeOption = newData;
          this.officeOption.unshift({
            value: null,
            label: "全部"
          });
          this.offLoad = false;
        })
        .catch(error => {
          this.offLoad = false;
          this.$message.error(error);
        });
      // 医院类型
      const datas = {
        pageNum: 0,
        pageSize: 2000
      };
      findHospitalTagsList(datas).then(res => {
        const resData = res.data.data.list ? res.data.data.list : [];
        const newData = [];
        resData.forEach(e => {
          newData.push({
            value: e.id,
            label: e.name
          });
        });
        this.tagOption = newData;
        this.tagOption.unshift({
          value: null,
          label: "全部"
        });
      });
    },
    GoBack() {
      // this.$router.push("/StrictSelection");
      this.$confirm("是否离开当前页面？", "确认信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "返回主页",
        cancelButtonText: "取消返回"
      })
        .then(() => {
          this.$message({
            type: "info",
            message: "正在跳转主页"
          });
          this.$router.push("/StrictSelection");
        })
        .catch(action => {
          this.$message({
            type: "info",
            message: action === "cancel" ? "放弃操作" : "停留在当前页面"
          });
        });
    },
    //返回
    // Back() {

    // },
    //提交
    Submit(i) {
      // console.log(this.quesSelIds);
      // console.log("i", this.$refs[i]);
      //校验子组件必填
      let flag = this.$refs["Summary"].validateForm();
      if (flag) {
        console.log("okokoko");
        // this.$message.success('已OK');
      } else {
        // this.$message.error("保全信息不完整，请继续填写完整");
        this.activeName = "0";
        this.changfn(this.activeName, "now");
        this.$message({
          message: "信息不完整，请继续填写完整",
          type: "warning"
        });
        return;
      }
      let newData = [];
      let ischeck = false;

      // console.log(this.medicalInstitutions, 1111, this.$refs["child" + 0][0]);
      let len = this.medicalInstitutions.length;

      for (let a = 0; a < len; a++) {
        let examType = this.$refs["child" + a][0].examType;
        let b = this.$refs["child" + a][0].ArrModel;
        // console.log(b);

        b.forEach((item, index) => {
          // console.log('item',item)
          let quesType = examType + "_" + (index + 1);
          let obj = { examType: examType, quesType: quesType };

          if (!item.quesSelId) {
            ischeck = true;

            // console.log(item, a);
          }
          if (item.quesSelId == 2 && !item.selDescOne) {
            ischeck = true;

            // console.log(item, a);
          }
          if (item.quesSelId == 3 && !item.selDescTwo) {
            ischeck = true;

            // console.log(item, a);
          }
          // console.log("item.examType:1111", obj);
          let sobj = { ...item, ...obj };
          newData.push(sobj);
        });
        // console.log("b", b);
        // console.log("ischeck8888", ischeck, a);
        if (ischeck) {
          this.activeName = a + 1 + "";
          this.changfn(this.activeName, "now");
          this.$message({
            message: "请填写必要字段或原因",
            type: "warning"
          });
          return;
        }
      }

      // console.log("newData", newData);
      // newData.map(res=>{
      //    // item.quesType =
      //     //   this.$refs["child" + a][0].examType + "_" + (index + 1);
      // })
      this.ids = newData;
      // if(this.type==2){
      //    console.log('this.form.examQuesSelInfos',this.form.examQuesSelInfos)
      //   this.form.examQuesSelInfos1=this.form.examQuesSelInfos.slice(0,245)
      //   this.form.examQuesSelInfos2=this.form.examQuesSelInfos.slice(245,490)
      //   this.form.examQuesSelInfos2.forEach((item,index)=>{
      //     this.form.examQuesSelInfos1[index].selDesc =this.form.examQuesSelInfos2[index].selDesc
      //   })
      //  this.form.examQuesSelInfos=this.form.examQuesSelInfos1
      // }else{
      this.form["examQuesSelInfos"] = newData;

      // }
      // console.log(this.form["examQuesSelInfos"]);
      // console.log("this.form", this.form);
      this.form.examQuesSelInfos.forEach((item, index) => {
        // console.log(item)
        this.form.examQuesSelInfos[index].quesSelId = newData[index].quesSelId;
        this.form.examQuesSelInfos[index].selDesc =
          this.form.examQuesSelInfos[index].quesSelId == 2
            ? this.form.examQuesSelInfos[index].selDescOne
            : (this.form.examQuesSelInfos[index].selDesc =
                this.form.examQuesSelInfos[index].quesSelId == 3
                  ? this.form.examQuesSelInfos[index].selDescTwo
                  : "");
      });
      console.log("examQuesSelInfos", this.form.examQuesSelInfos);

      addHospitalExam(this.form).then(res => {
        // console.log("res", res);
        if (res.data.code == 0) {
          this.$router.push("/StrictSelection");
        }
      });
    },
    slicefun(index) {
      index = 0;
      if (this.sindex) {
        index = this.sindex;
      }
    },
    changfn(index, type) {
      this.$refs.carousel.setActiveItem(type ? index : index - 0 + 1);
      // document.body.scrollTop = document.documentElement.scrollTop = 0
      document.getElementsByClassName("app-main")[1].scrollTop = 0;

      if (!type) {
        this.activeName =
          index == this.medicalInstitutions.length ? "0" : index + 1 + "";
        // console.log(index);
      }
    },
    handleClick(tab, event) {
      // console.log(tab, event, this.activeName);
      this.changfn(this.activeName, "now");
    }
  }
};
</script>
<style scoped>
.el-button--medium {
  padding: 10px 20px;
  font-size: 14px;
  border-radius: 4px;
  margin: 30px;
}
</style>
